/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.rayson.share.http;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.rayson.api.annotation.NotNull;
import org.rayson.share.transport.ByteArrayBuffer;

/**
 * An abstract implementation of {@link HttpMessage}.
 * 
 * @param <S>
 *            Start line type.
 * @author creativor
 */
public abstract class HttpAbstractMessage<S extends HttpStartLine> implements
		HttpMessage {
	private S startLine;
	private final Map<String, HttpHeader> headers;
	private byte[] body;
	private int bodyLength;

	private static final int EMPTY_BODY_LENGTH = 0;
	private final static byte[] DUMMMY_BODY = new byte[EMPTY_BODY_LENGTH];

	protected HttpAbstractMessage() {
		this.headers = new HashMap<>();
		body = DUMMMY_BODY.clone();
		bodyLength = EMPTY_BODY_LENGTH;
	}

	@Override
	public void addHeader(final HttpHeader header) {
		final String name = header.getName();
		if (name.equals(HttpConstants.CONTENT_LENGTH_HEADER_NAME)) {
			bodyLength = Integer.parseInt(header.getValue());
		}
		headers.put(name, header);
	}

	@Override
	public final byte[] getBody() {
		return body;
	}

	/**
	 * Get {@link HttpConstants#CONTENT_LENGTH_HEADER_NAME} header value of this
	 * message.
	 * 
	 * @return Found header value. Or 0 if no such header found.
	 */
	@Override
	public final int getBodyLength() {
		if (bodyLength >= 0)
			return bodyLength;
		final HttpHeader header = headers
				.get(HttpConstants.CONTENT_LENGTH_HEADER_NAME);
		if (header == null)
			return 0;
		else
			return Integer.valueOf(header.getValue());
	}

	@Override
	public HttpHeader getHeader(final String name) {
		return headers.get(name);
	}

	@Override
	public Map<String, HttpHeader> getHeaders() {
		return java.util.Collections.unmodifiableMap(headers);
	}

	@Override
	public final S getStartLine() {
		return startLine;
	}

	/**
	 * @param body
	 *            the body to set
	 */
	public void setBody(@NotNull final byte[] body) {
		this.body = body;
	}

	/**
	 * @param startLine
	 *            the start line to set
	 */
	public final void setStartLine(@NotNull final S startLine) {
		this.startLine = startLine;
	}

	@Override
	public String toString() {
		final StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("startLine:" + this.startLine);
		sb.append(", headers:" + this.headers);
		sb.append(", body:" + Arrays.toString(this.body));
		sb.append("}");
		return sb.toString();
	}

	@Override
	public void writeTo(final ByteArrayBuffer buffer) {
		this.getStartLine().writeTo(buffer);
		for (final HttpHeader header : headers.values()) {
			header.writeTo(buffer);
		}
		buffer.write(HttpConstants.CRLF);
		buffer.write(getBody());
	}
}